import netifaces as ni ###external
import json
import zlib
import uuid
AF_INET=2
AF_INET6=10
AF_PACKET=17



TYPE_INIT=0
TYEP_REGISTER=1
TYPE_MISSPOLICY=2
TYPE_RECONNECT=3

TYPE_POLICY_ADD=4
TYPE_POLICY_UPDATE=5
TYPE_POLICY_DEL=6
TYPE_POLICY_GET=8
TYPE_POLICY_LIST=9
TYPE_POLICY_MOVE=10

TYPE_GROUP_BUILD=11
TYPE_GROUP_ADD=12
TYPE_GROUP_DEL=13
TYPE_GROUP_MOVE=14
TYPE_GROUP_GET=15
TYPE_GROUP_LIST=16


TYPE_GUARD_LIST=17
TYPE_GUARD_GET=18
TYPE_APP_ADD=19
TYPE_UPDATE_CONTROL=20

TYPE_REP_REGISTER=50
TYPE_REP_MISSPOLICY=51
TYEP_REP_OPERS_OK=52
TYEP_REP_OPERS_ERR=53

TYPE_GUARD_DEBUG=100
TYPE_REP_GUARD_DEBUG=101
TYPE_USR_DEBUG=102
TYPE_REP_USR_DEBUG=103

MSG_SENDER="sender"
MSG_REQUESTER="app"
MSG_BODY="body"
MSG_TARGET="target"
MSG_TYPE="type"
MSG_FROM="from"
MSG_TO="to"
MSG_FAIL="failinfo"


def get_host_info():
    host_info={}
    for nf in ni.interfaces():
        if nf !="lo":
            host_info[nf]={}
            info=ni.ifaddresses(nf)
            host_info[nf]['mac']=info[AF_PACKET][0]['addr']
            host_info[nf]['bc']=info[AF_INET][0]['broadcast']
            host_info[nf]['nm']=info[AF_INET][0]['netmask']
            host_info[nf]['ip']=info[AF_INET][0]['addr']
    return host_info

def pack_msg(msg,flag=False):
    if flag==True:
        return zlib.compress(json.dumps(msg),zlib.Z_BEST_SPEED)

    else:
        return json.dumps(msg)

def unpack_msg(msg,flag=False):
    if flag==True:
        return eval(zlib.decompress(msg))
    else:
        return eval(msg)


def generate_id():
    return str(uuid.uuid1()).replace("-","")[0:10]


class ErrLog(object):
    """docstring for err_log"""
    def __init__(self):
        self.res=[]
        self.flag=True
    
    def append(self,info):
        self.res.append(str(info))
        self.flag=False

    def clear(self):
        self.res=[]
        self.flag=True
    
    def __str__(self):
        return "\n".join(self.res)

def error_msg():
    msg={}
    msg[MSG_SENDER]="test"
    msg[MSG_TYPE]=TYEP_REP_OPERS_ERR
    msg[MSG_BODY]="error"
    return json.dumps(msg)

        
class Message(object):
    """docstring for MSG"""

    def __init__(self):
        self.compress=False
        pass

    def msg_header(self):
        pass

    def msg_reg_new(self,mid):
        msg={}
        msg[MSG_SENDER]=mid
        msg[MSG_TYPE]=TYEP_REGISTER
        msg[MSG_BODY]=get_host_info()
        return json.dumps(msg)

    def msg_req_in(self,mid,fid):
        msg={}
        msg["id"]=mid
        msg["from_id"]=fid
        msg["type"]="req_in"
        msg["body"]=get_host_info()
        return json.dumps(msg)

if __name__ == '__main__':
    e=ErrLog()
    e.append("bbb")
    e.append("aaa")
    print str(e)